import express from 'express';
import {client} from './scheme.js';
import type { bill } from '@prisma/client';

const routeFeature = express.Router();

routeFeature.post('/addAccount', async (req, res) => {
  const {param: {user, accountConfig}} = req.body;
  try {
    console.log(user.email);
    const userProfile = await client.user.findFirstOrThrow({
      where: {email: user.email}
    });
    const operationResult = await client.account.create({
      data: {
        accountName: accountConfig.name,
        priority: accountConfig.priority,
        type: accountConfig.type,
        ownerID: userProfile.userID
      }
    });
    if(operationResult) {
      return res.status(200).json({
        timestamp: new Date().getTime(),
        api: {version: 'v1.0', status: 200},
        result: {
          description: '添加成功',
          email: userProfile.email,
          accountID: operationResult.accountID,
          accountConfig: {
            name: operationResult.accountName,
            priority: operationResult.priority,
            type: operationResult.type
          }
        }
      });
    }
  } catch (userNotFount) {
    console.log(userNotFount);
    return res.status(404).json({
      timestamp: new Date().getTime(),
      api: {version: 'v1.0', status: 401},
      result: {description: '无法找到用户'}
    });
  }
});

routeFeature.post('/editAccount', async (req, res) => {
  const {param: {target: {accountID, isDelete, newAccountConfig}}} = req.body;
  if(isDelete) {
    const operationResult = await client.account.delete({
      where: {accountID: accountID}
    });
    if(operationResult) {
      return res.json({
        timestamp: new Date().getTime(),
        api: {version: 'v1.0', status: 200},
        result: {
          description: '删除成功',
          target: {
            accountID: accountID,
            isDelete: isDelete,
            newAccountConfig: newAccountConfig
          }
        }
      });
    }
  } else {
    const {name, priority, type} = newAccountConfig;
    const operationResult = await client.account.update({
      where: {accountID: accountID},
      data: {
        accountName: name,
        priority: priority,
        type: type
      }
    });
    if(operationResult) {
      return res.json({
        timestamp: new Date().getTime(),
        api: {version: 'v1.0', status: 200},
        result: {
          description: '修改成功',
          target: {
            accountID: accountID,
            isDelete: isDelete,
            newAccountConfig: newAccountConfig
          }
        }
      });
    }
  }
});

routeFeature.post('/getAccounts', async (req, res) => {
  const {param: {user: {email}, filter}} = req.body;
  if(filter === undefined) {
    const owner = await client.user.findFirstOrThrow({where: {email: email}});
    const operationResult = await client.account.findMany({
      where: {ownerID: owner.userID}
    });
    return res.json({
      timestamp: new Date().getTime(),
      api: {version: 'v1.0', status: 200},
      result: {
        description: '查询成功',
        queryData: operationResult.map((elem) => {
          return {
            accountID: elem.accountID,
            name: elem.accountName,
            priority: elem.priority,
            type: elem.type,
          };
        })
      }
    });
  } else {
    const owner = await client.user.findFirstOrThrow({where: {email: email}});
    const operationResult = await client.account.findMany({
      where: {ownerID: owner.userID, type: filter.type}
    });
    return res.json({
      timestamp: new Date().getTime(),
      api: {version: 'v1.0', status: 200},
      result: {
        description: '查询成功',
        queryData: operationResult.map((elem) => {
          return {
            accountID: elem.accountID,
            name: elem.accountName,
            priority: elem.priority,
            type: elem.type,
          };
        })
      }
    });
  }
});

routeFeature.post('/addBill', async (req, res) => {
  const {param: {user, billConfig}} = req.body;
  const userProfile = await client.user.findFirstOrThrow(
    { where: {email: user.email} }
  );
  try {
    const {time, cost, tag, expression, type, account} = billConfig;
    const operationResult = await client.bill.create({
      data: {
        time: new Date(time),
        cost: cost,
        tag: tag,
        expression: expression,
        billType: type,
        accountID: account
      }
    });
    if(operationResult) {
      return res.json({
        timestamp: new Date().getTime(),
        api: {version: 'v1.0', status: 200},
        result: {
          description: '创建成功',
          email: userProfile.email,
          userID: userProfile.userID,
          billID: operationResult.billID
        }
      });
    }
  } catch(e) {
    console.log(e);
    return res.json({
      timestamp: new Date().getTime(),
      api: {version: 'v1.0', status: 400},
      result: {description: '创建失败'}
    });
  }
});

routeFeature.post('/editBill', async (req, res) => {
  const {param: {target}} = req.body;
  const {billID, isDelete, newBillConfig} = target;
  if(isDelete) {
    const operationResult = await client.bill.delete({
      where: {billID: billID}
    });
    if(operationResult) {
      return res.json({
        timestamp: new Date().getTime(),
        api: {version: 'v1.0', status: 200},
        result: {
          description: '删除成功',
          target: {...target}
        }
      });
    }
  } else {
    const operationResult = await client.bill.update({
      where: {billID: billID},
      data: {
        time: new Date(newBillConfig.time),
        cost: newBillConfig.cost,
        tag: newBillConfig.tag,
        expression: newBillConfig.expression,
        billType: newBillConfig.type,
        accountID: newBillConfig.account
      }
    });
    if(operationResult) {
      return res.json({
        timestamp: new Date().getTime(),
        api: {version: 'v1.0', status: 200},
        result: {
          description: '修改成功',
          target: {...target}
        }
      });
    }
  }
});

routeFeature.post('/getBills', async (req, res) => {
  const {param: {user, filter}} = req.body;
  const userAccounts = await client.user.findFirstOrThrow({
    where: {email: user.email},
    include: {account: true}
  });
  const accountID2name = userAccounts.account.map((elem) => {
    return {
      id: elem.accountID,
      name: elem.accountName
    };
  });
  const {activate: {time, type, account, cost}} = filter;
  const queryData: Array<Promise<bill[]>> = [];
  if(account === true) {
    userAccounts.account = userAccounts.account.filter(
      (elem) => elem.accountID === filter.account
    );
  }
  if(type === true) {
    userAccounts.account.map((elem) => {
      queryData.push(
        client.bill.findMany({
          where: {accountID: elem.accountID, billType: filter.type}
        })
      );
    });
  } else {
    userAccounts.account.map((elem) => {
      queryData.push(
        client.bill.findMany({ where: {accountID: elem.accountID} })
      );
    });
  }
  let rawData = (await Promise.all(queryData)).flat();
  if(time !== undefined && time !== false && time) {
    rawData = rawData.filter((elem) => {
      const {from, to} = filter.time;
      return (elem.time >= new Date(from) && elem.time <= new Date(to));
    });
  }
  if(cost !== undefined && cost !== false && cost) {
    rawData = rawData.filter((elem) => {
      const [min, max] = filter.cost;
      return (elem.cost >= min && elem <= max);
    });
  }
  return res.json({
    timestamp: new Date().getTime(),
    api: {version: 'v1.0', status: 200},
    result: {
      description: '查询成功',
      queryData: rawData.map((elem) => {
        return {
          billID: elem.billID,
          time: elem.time,
          cost: elem.cost,
          tag: elem.tag,
          type: elem.billType,
          account: elem.accountID,
          accountName: accountID2name.find((kvPair) => kvPair.id === elem.accountID)?.name,
          expression: elem.expression
        };        
      })
    }
  });
});

export default routeFeature;